<?php
/**
 * 设计师大赛奖项相关功能控制器
 */
namespace Beerus\Modules\DesignerCompetition\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DesignerCompetition\DcAward;
use Doraemon\service\DesignerCompetition\DcCommon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AwardController extends Controller
{
    const PAGE_SIZE = 15;

    const AWARD_YEARS = [
        1=>2021,
        2=>2022,
        3=>2024,

    ];
    const AWARD_TEARS_INDEX = [
        2021=>1,
        2022=>2,
        2024=>3,
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 设计师大赛奖项列表
    public function index(Request $request, Content $content)
    {
        $request_params = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
        if (!empty($request_params['id'])) {
            $condition['id'] = $request_params['id'];
        }
        if (!empty($request_params['award_parent_id'])) {
            $condition['award_parent_id'] = $request_params['award_parent_id'];
        }
        if (!empty($request_params['award_year'])) {
            $condition['award_year'] = $request_params['award_year'];
        }
        $condition['data_status'] = DcAward::STATUS_NORMAL;
        $condition['ORDER'] = [
            'award_year' => 'DESC',
            'award_sort' => 'ASC'
        ];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $tips = [];
        return $content
            ->header('设计师奖项列表')
            ->row($tips)
            ->row($this->indexGrid($condition));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition)
    {
        $lists = DcAward::select('*', $condition);
        unset($condition['ORDER']);
        unset($condition['LIMIT']);

        $total = DcAward::count($condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('id', '奖项ID')->placeholder('请输入奖项ID');
                    });
                    $filter->year('award_year', '奖项年份');
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('award_parent_id', '奖项父级ID')->placeholder('请输入奖项ID');
                    });
                    $filter->expand();
                });
                $grid->column('id', '奖项id');
                $grid->column('award_name', '奖项名称');
                $grid->column('award_year', '奖项年份');
                $grid->column('award_type', '奖项类型')->display(function() {
                    return DcCommon::getAwardTypes($this->award_year)[$this->award_type];
                });
                $grid->column('award_num', '奖项个数');
                $grid->column('award_sort', '奖项顺序');
                $grid->column('award_show_name', '前端显示名称');
                $grid->column('award_show_desc', '前端显示描述');
                $grid->column('award_show_intro', '前端显示作品介绍说明');
            }
        );
        return $gridList;
    }

    // 新增/修改奖项信息
    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '新增';
        } else {
            $is_create = false;
            $header = '修改';
        }

        $tab = new Tab();
        $tab->add('奖项信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '设计师奖项列表',
                'url' => route('award.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = DcAward::get('*', ['id' => $id]);
            $data['award_year'] = self::AWARD_TEARS_INDEX[$data['award_year']];
            $form = new Form($data);
            $form->text('id', '奖项ID')->setWidth(4, 2)->readOnly();
        }
        $form->text('award_name', '奖项名称')->setWidth(4, 2)->required('不能为空');
        $form->text('award_parent_id', '奖项父级id')->setWidth(4, 2)->required('不能为空');
        $form->select('award_year', '奖项年份')
            ->options(self::AWARD_YEARS)
            ->when('=', 1, function(Form $form) {
                $form->select('award_type', '奖项类型')->options(DcCommon::getAwardTypes(2021))->setWidth(4, 2);
            })
            ->when('=', 2, function(Form $form) {
                $form->select('award_type', '奖项类型')->options(DcCommon::getAwardTypes(2022))->setWidth(4, 2);
            })
            ->when('=', 3, function(Form $form) {
                $form->select('award_type', '奖项类型')->options(DcCommon::getAwardTypes(2024))->setWidth(4, 2);
            })
            ->setWidth(4, 2)
            ->default(2)
            ->required('不能为空');
        $form->number('award_num', '奖项数')->default(0)->min(0);
        $form->number('award_sort', '奖项顺序')->default(0)->min(0);
        $form->text('award_show_name', '前端显示奖项名称')->setWidth(4, 2);
        $form->text('award_show_desc', '前端显示奖项描述')->setWidth(4, 2);
        $form->text('award_show_intro', '前端显示作品介绍提醒')->setWidth(4, 2);

        $form->action('/admin/DesignerCompetition/award/save');
        return $form->render();
    }

    // 编辑奖项
    public function editSubmit(Request $request)
    {
        $data = $request->all();
        unset($data['_token']);
        $cur_time = time();
        $data['award_year'] = self::AWARD_YEARS[$request['award_year']];
        if (isset($request['id'])) {
            $data['edit_time'] = $cur_time;
            $rs = DcAward::updateInfo($data, ['id' => $request['id']]);
        } else {
            $item = DcAward::getAwardByNameAndYear($data['award_parent_id'], $data['award_name'], $data['award_year']);
            if (!empty($item)) {
                $error = new MessageBag(['title' => '已存在同名奖项']);
                return back()->with(compact('error'));
            }
            $item = DcAward::getAwardBySortAndYear($data['award_parent_id'], $data['award_sort'], $data['award_year']);
            if (!empty($item)) {
                $error = new MessageBag(['title' => '已存在同顺序奖项']);
                return back()->with(compact('error'));
            }
            $data['add_time'] = $cur_time;
            $data['data_status'] = DcAward::STATUS_NORMAL;
            $rs = DcAward::addInfo($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if (!$rs) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/DesignerCompetition/award')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $award = DcAward::getAwardInfoById($id);
        if ($award) {
            // 确认当前奖项是否有作品绑定
//            if (DesignerAwardSign2020::getAwardCntByAwardId($id) > 0) {
//                return response()->json([
//                    'award_status' => false,
//                    'message' => '有获得该奖项作品，请取消后再操作',
//                ]);
//            }
            $data['data_status'] = DcAward::STATUS_DELETE;
            $data['edit_time'] = time();
            $rs = DcAward::update($data, ['id' => $id]);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            }
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json([
            'status' => false,
            'message' => "操作失败",
        ]);
    }
}
